<template>
  <li :class="['toc-item', 'level-' + node.level, { active: node.id === activeId }]">
    <div class="toc-item__row" @click="onNavigate" :title="node.text">
      <span class="toc-item__text">{{ node.text }}</span>
      <span class="toc-item__meta">
        <button class="toc-insert" title="在此处插入卡片" @click.stop="onInsert">＋</button>
      </span>
    </div>
    <ul v-if="node.children && node.children.length" class="toc__list">
      <TocNodeItem
        v-for="c in node.children"
        :key="c.id"
        :node="c"
        :active-id="activeId"
        @navigate="$emit('navigate', $event)"
        @insertCardUnder="$emit('insertCardUnder', $event)"
      />
    </ul>
  </li>
</template>

<script lang="ts" setup>
defineOptions({ name: 'TocNodeItem' })
interface TocCounts { cards: number; images: number; links: number }
interface TocNode { id: string; level: 1 | 2 | 3; text: string; children: TocNode[]; counts: TocCounts }
const props = defineProps<{ node: TocNode; activeId?: string }>()
const emit = defineEmits<{ (e: 'navigate', id: string): void; (e: 'insertCardUnder', id: string): void }>()

function onNavigate() { emit('navigate', props.node.id) }
function onInsert() { emit('insertCardUnder', props.node.id) }
</script>

<style scoped>
.toc__list { list-style: none; margin: 0; padding: 6px; }
.toc-item { margin: 2px 0; }
.toc-item__row { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 6px 8px; border-radius: 8px; cursor: pointer; }
.toc-item__row:hover { background: #f5f7fa; }
.toc-item.active > .toc-item__row { background: #eaf3fe; border-left: 3px solid #3d99f5; }
.toc-item__text { display: inline-block; max-width: 180px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.toc-badge { font-size: 12px; color: #60758a; margin-left: 6px; }
.toc-insert { margin-left: 6px; border: none; background: #eaf3fe; color: #3d99f5; border-radius: 6px; padding: 2px 6px; cursor: pointer; }
.toc-insert:hover { background: #d7e9fe; }
.level-1 > .toc-item__row { padding-left: 8px; }
.level-2 > .toc-item__row { padding-left: 20px; }
.level-3 > .toc-item__row { padding-left: 32px; }
</style>
